﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Meqs.Entity;
using Meqs.Logic.Interface;

public partial class Education_School : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    //初始化 repeat控件
    protected void btnBind_Click(object sender, EventArgs e)
    {
        Bind(1);
    }

    private void Bind(int pageIndex)
    {
        //获取查询条件类型和值
        int qType = int.Parse(HFQueryType.Value);
        int qValue_Area = int.Parse(HFQueryValue_Area.Value);
        int qValue_Option = int.Parse(HFQueryValue_Option.Value);
        string qValue_Name = HFQueryValue_Name.Value;

        ISchoolInfoLogic schoolInfoLogic = Container<ISchoolInfoLogic>.Instance;
        List<VSchoolInfo> list = null;
        Hashtable ht = new Hashtable();

        switch (qType)
        {
            //0: 查询所有
            case 0:
                //根据条件查询数据库
                ht.Add("IsEffect", true);
                list = (List<VSchoolInfo>)schoolInfoLogic.FindVSchoolInfo(ht);

                //转换学校性质
                foreach (VSchoolInfo si in list)
                {
                    si.SchoolOptName = Common.ConvertSchoolOptNum(si.SchoolOpt);
                } 

                //分页处理
                PagerBind(list, pageIndex);

                break;
            //1: 按其他条件查询
            case 1:
                //根据条件查询数据库
                if (qValue_Area != 0)
                    ht.Add("AreaID", qValue_Area);
                if (qValue_Option != 0)
                    ht.Add("SchoolOpt", qValue_Option);
                ht.Add("SchoolName", qValue_Name);
                ht.Add("IsEffect", true);
                list = (List<VSchoolInfo>)schoolInfoLogic.FindVSchoolInfo(ht);

                //转换学校性质
                foreach (VSchoolInfo si in list)
                {
                    si.SchoolOptName = Common.ConvertSchoolOptNum(si.SchoolOpt);
                } 

                //分页处理
                PagerBind(list, pageIndex);

                break;
            default:
                break;
        }
    }

    //分页处理
    private void PagerBind(List<VSchoolInfo> srcList, int pageIndex)
    {
        AspNetPager1.RecordCount = srcList.Count;
        AspNetPager1.CurrentPageIndex = pageIndex;

        int index = (pageIndex - 1) * AspNetPager1.PageSize;
        int count = 0;
        if (srcList.Count - index >= AspNetPager1.PageSize) count = AspNetPager1.PageSize;
        else count = srcList.Count - index;

        List<VSchoolInfo> pageList = srcList.GetRange(index, count);

        Repeater1.DataSource = pageList;
        Repeater1.DataBind();
    }

    protected void AspNetPager1_PageChanged(object src, EventArgs e)
    {
        Wuqi.Webdiyer.PageChangedEventArgs pc = e as Wuqi.Webdiyer.PageChangedEventArgs;

        Bind(pc.NewPageIndex);
    }

    /// <summary>
    /// 添加学校信息
    /// </summary>
    /// <param name="schoolInfo"></param>
    /// <returns></returns>
    [System.Web.Services.WebMethod]
    public static int InsertSchoolInfo(SchoolInfo schoolInfo)
    {
        //添加学期信息
        IGlobalTermInfoLogic globalTermInfoLogic = Container<IGlobalTermInfoLogic>.Instance;
        List<GlobalTermInfo> globalTermInfoList = (List<GlobalTermInfo>)globalTermInfoLogic.FindAll();
        if ((globalTermInfoList == null) || (globalTermInfoList.Count == 0))
            return -1;
        schoolInfo.SchoolYear = globalTermInfoList[0].GlobalYear;
        schoolInfo.SchoolTerm = (byte)globalTermInfoList[0].GlobalTerm;

        //创建新学校
        schoolInfo.IsEffect = true;
        schoolInfo.SchoolMark = "";                             //SchoolMark字段不能为空，数据库约束添加空字符串
        int schoolId = Container<ISchoolInfoLogic>.Instance.Create(schoolInfo);
        if (schoolId > 0)
        {
            //自动生成SchoolMark,并更新
            string str = "S00000";
            string sSchoolId = schoolId.ToString();
            string sHeader = str.Substring(0, str.Length - sSchoolId.Length);
            schoolInfo.SchoolMark = sHeader + sSchoolId;
            Container<ISchoolInfoLogic>.Instance.Update(schoolInfo);

            //设置学校用户权限(文件夹路径从Web.Config读取)
            IDbManagerLogic dbManagerLogic = Container<IDbManagerLogic>.Instance;

            if (!dbManagerLogic.CreateDbUser(schoolInfo.SchoolMark, HttpContext.Current.Server.MapPath("../../Config/Script")))
                return -2;

            //添加学校管理员
            TeacherInfo schoolAdminInfo = new TeacherInfo(0, "admin", "admin", Common.GetStartPwd(), 0, DateTime.Now, DateTime.Now, true, 1, schoolInfo.SchoolMark, "admin");
            int adminId = Container<ITeacherInfoLogic>.Instance.Create(schoolAdminInfo);
        }

        return schoolId;
    }

    /// <summary>
    /// 修改学校信息
    /// </summary>
    /// <param name="schoolInfo"></param>
    /// <returns></returns>
    [System.Web.Services.WebMethod]
    public static int UpdateSchoolInfo(SchoolInfo schoolInfo)
    {
        ISchoolInfoLogic schoolInfoLogic = Container<ISchoolInfoLogic>.Instance;

        //更新时保留原来的学期学年设置
        SchoolInfo si = schoolInfoLogic.FindById(schoolInfo.RID);
        if (si == null) return 0;
        schoolInfo.SchoolMark = si.SchoolMark;
        schoolInfo.SchoolYear = si.SchoolYear;
        schoolInfo.SchoolTerm = si.SchoolTerm;
        schoolInfo.IsEffect = true;

        return schoolInfoLogic.Update(schoolInfo);
    }

    /// <summary>
    /// 删除学校信息(设置有效字段为False)
    /// </summary>
    /// <param name="schoolId"></param>
    /// <returns></returns>
    [System.Web.Services.WebMethod]
    public static int DeleteSchoolInfo(int schoolId)
    {
        int result = 0;

        ISchoolInfoLogic schoolInfoLogic = Container<ISchoolInfoLogic>.Instance;
        SchoolInfo schoolInfo = schoolInfoLogic.FindById(schoolId);
        if (schoolInfo != null)
        {
            schoolInfo.IsEffect = false;
            result = schoolInfoLogic.Update(schoolInfo); 
        }

        return result;
    }

    //查询学校信息（根据ID）
    [System.Web.Services.WebMethod]
    public static SchoolInfo SelectSohoolInfo(int schoolId)
    {
        ISchoolInfoLogic schoolInfoLogic = Container<ISchoolInfoLogic>.Instance;
        SchoolInfo si = schoolInfoLogic.FindById(schoolId);
        return si;
    }

    //验证学校编号和学校名字，不能重复
    [System.Web.Services.WebMethod]
    public static int ValidateSchoolInfo(SchoolInfo schoolInfo)
    {
        int result = 0;
        ISchoolInfoLogic schoolInfoLogic = Container<ISchoolInfoLogic>.Instance;

        //1.新增
        if (schoolInfo.RID == 0)
        {
            Hashtable tableCode = new Hashtable();
            tableCode.Add("SchoolCode", schoolInfo.SchoolCode);
            tableCode.Add("IsEffect", 1);
            result = schoolInfoLogic.FindCount(tableCode);
            //学校编号重复
            if (result > 0) 
                return 1;

            if (tableCode.ContainsKey("IsEffect"))
                tableCode["IsEffect"] = 0;

            result = schoolInfoLogic.FindCount(tableCode);
            //学校编号重复
            if (result > 0)
                return 2;       //在无效数据里面已经存在这个学校编号，则返回2  

            Hashtable tableName = new Hashtable();
            tableName.Add("SchoolName", schoolInfo.SchoolName);
            tableName.Add("IsEffect", 1);
            result = schoolInfoLogic.FindCount(tableName);
            //学校名称重复
            if (result > 0) 
                return 3;

            if (tableName.ContainsKey("IsEffect"))
                tableName["IsEffect"] = 0;

            result = schoolInfoLogic.FindCount(tableName);
            //学校编号重复
            if (result > 0)
                return 4;       //在无效数据里面已经存在这个学校编号，则返回2  
        }
        //2.修改
        else
        {
            SchoolInfo si = schoolInfoLogic.FindById(schoolInfo.RID);
            //修改了学校编号
            if (si.SchoolCode.ToUpper() != schoolInfo.SchoolCode.ToUpper())
            {
                //修改条件：教工、学生、班级、课程四个表中没有相关记录
                //ITeacherInfoLogic teacherInfoLogic = Container<ITeacherInfoLogic>.Instance;
                //IStudentInfoLogic studentInfoLogic = Container<IStudentInfoLogic>.Instance;
                //IClsInfoLogic clsInfoLogic = Container<IClsInfoLogic>.Instance;
                //ICauseInfoLogic causeInfoLogic = Container<ICauseInfoLogic>.Instance;
                //Hashtable htCount = new Hashtable();
                //htCount.Add("SchoolMark", si.SchoolMark);
                //if ((teacherInfoLogic.FindCount(htCount) > 0)  ||
                //     (studentInfoLogic.FindCount(htCount) > 0) ||
                //     (clsInfoLogic.FindCount(htCount) > 0)     ||
                //     (causeInfoLogic.FindCount(htCount) > 0)    )
                //    return 5;

                Hashtable tableCode = new Hashtable();
                tableCode.Add("SchoolCode", schoolInfo.SchoolCode);
                tableCode.Add("IsEffect", 1);
                result = schoolInfoLogic.FindCount(tableCode);
                //学校编号重复
                if (result > 0) 
                    return 1;

                if (tableCode.ContainsKey("IsEffect"))
                    tableCode["IsEffect"] = 0;

                result = schoolInfoLogic.FindCount(tableCode);
                //学校编号重复
                if (result > 0)
                    return 2;       //在无效数据里面已经存在这个学校编号，则返回2  
            }

            //修改了学校名称
            if (si.SchoolName.ToUpper() != schoolInfo.SchoolName.ToUpper())
            {
                Hashtable tableName = new Hashtable();
                tableName.Add("SchoolName", schoolInfo.SchoolName);
                tableName.Add("IsEffect", 1);
                result = schoolInfoLogic.FindCount(tableName);
                //学校名称重复
                if (result > 0) 
                    return 3;

                if (tableName.ContainsKey("IsEffect"))
                    tableName["IsEffect"] = 0;

                result = schoolInfoLogic.FindCount(tableName);
                //学校编号重复
                if (result > 0)
                    return 4;       //在无效数据里面已经存在这个学校编号，则返回2  
            }
        }

        return result;
    }

    //获取学区信息
    [System.Web.Services.WebMethod]
    public static List<SchoolArea> GetSchoolAreaList()
    {
        ISchoolAreaLogic schoolAreaLogic = Container<ISchoolAreaLogic>.Instance;
        return (List<SchoolArea>)schoolAreaLogic.FindAll();
    }

    //重置学校管理员密码
    [System.Web.Services.WebMethod]
    public static int ResetAdminPsd(int schoolId)
    {
        int result = 0;

        ISchoolInfoLogic  schoolInfoLogic   = Container<ISchoolInfoLogic>.Instance;
        ITeacherInfoLogic teacherInfoLogic  = Container<ITeacherInfoLogic>.Instance;

        SchoolInfo schoolInfo = schoolInfoLogic.FindById(schoolId);
        if (schoolInfo != null)
        {
            Hashtable ht = new Hashtable();
            ht.Add("SchoolMark", schoolInfo.SchoolMark);
            ht.Add("IsAdmin", 1);
            ht.Add("IsEffect", true);
            List<TeacherInfo> teacherInfoList = (List<TeacherInfo>)teacherInfoLogic.FindAll(ht);
            if (teacherInfoList == null) return 0;

            if (teacherInfoList.Count > 0)
            {
                string strStartPwd = Common.GetStartPwd();
                List<int> idList = new List<int>();
                idList.Add(teacherInfoList[0].RID);
                result = teacherInfoLogic.ResetPassword(strStartPwd, idList);
            }
        }

        return result;
    }
}
